/*******************************************************************************
 * Copyright 2007, 2009 InnovaSoft SA http://www.innovasoft.biz/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
 
package biz.innovasoft.nodb.query;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class MultinaryExpression extends Expression {

	public List<Expression> expressions = new ArrayList<Expression>();

	public MultinaryExpression(Operator operator, Expression... expressions) {
		this.operator = operator;
		for (Expression expression : expressions) {
			this.expressions.add(expression);
		}
	}

	public MultinaryExpression(Operator operator, Expression left,
			Expression... expressions) {
		this.operator = operator;
		this.left = left;
		for (Expression expression : expressions) {
			this.expressions.add(expression);
		}
	}

	public MultinaryExpression and(Expression... expressions) {
		return new MultinaryExpression(Operator.AND, this, expressions);
	}

	public MultinaryExpression or(Expression... expressions) {
		return new MultinaryExpression(Operator.OR, this, expressions);
	}

	public String toString() {
		StringBuffer buffer = new StringBuffer();
		if (left != null) {
			buffer.append(left.toString());
		}
		switch (operator) {
		case AND:
			buffer.append(getString(" AND "));
			break;
		case OR:
			buffer.append(getString(" OR "));
		}

		return buffer.toString();
	}

	private String getString(String op) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("(");
		for (int t = 0; t < expressions.size(); t++) {
			if (t > 0)
				buffer.append(op);
			buffer.append(expressions.get(t).toString());
		}
		buffer.append(")");
		return buffer.toString();
	}
	
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj);
	}

	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

}
